/**  
 * Copyrights@2006, Tianyuan DIC Information Co.,Ltd.
 * 文件名:    TMallOrderQueryHandle.java  
 * 描述:   
 * 作者:     kaiyang
 * 版本:    1.0  
 * 创建时间:   2015年5月4日 下午2:44:53  
 *  
 * 修改历史:  
 * 日期                          作者           版本         描述  
 * ------------------------------------------------------------------  
 * 2015年5月4日      kaiyang      1.0        1.0 Version  
 */ 
package com.hp.bon.sgw.wh.channel.handler;

import java.io.IOException;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import java.util.Map.Entry;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import com.hp.bon.sgw.Constants;
import com.hp.bon.sgw.Constants.MessageType;
import com.hp.bon.sgw.bean.XmlMessage;
import com.hp.bon.sgw.core.BuzProcessorManager;
import com.hp.bon.sgw.core.CallParam;
import com.hp.bon.sgw.core.channel.SoapChannel;
import com.hp.bon.sgw.core.channel.handler.IAsynCallHandler;
import com.hp.bon.sgw.domain.MessageDetail;
import com.hp.bon.sgw.threads.MessageDetailCacheManager;
import com.hp.bon.sgw.threads.TaskManager;
import com.hp.bon.sgw.wh.bean.tmall.TMallOrderBean;
import com.hp.bon.sgw.wh.channel.TMallChannel;
import com.hp.bon.sgw.wh.service.TMallResponseService;
import com.hp.bon.sgw.wh.utils.SignUtilsImpl;
import com.hp.ocs.diameter.message.AVP;
import com.hp.ocs.diameter.message.AVP_Grouped;
import com.hp.ocs.diameter.message.AVP_UTF8String;
import com.hp.ocs.diameter.message.Message;

/**  
 * @ClassName: TMallOrderQueryHandle   
 * @Description: TODO  
 * @author: kaiyang  
 * @date:2015年5月4日 下午2:44:53 
 * 补     充:SGW手机订单查询 响应处理类 
 * @author C.J
 * @date 2017年12月5日 上午9:38:27 
 */
public class TMallOrderQueryHandle implements IAsynCallHandler{

	private static final Logger _log = LoggerFactory.getLogger(TaobaoFeeHandle.class);
	private PrintStream printStream;
	private TMallOrderBean tmallOrderBean;
	private TMallResponseService tmallResponseService;
	private ThreadPoolTaskExecutor asynExecutor;
	private String tmallRetUrl;
	private String pubKeyValue;
	
	public TMallOrderQueryHandle(PrintStream printStream,TMallOrderBean tmallOrderBean,TMallResponseService tmallResponseService,ThreadPoolTaskExecutor asynExecutor,String tmallRetUrl,String pubKeyValue)
	{
		this.printStream = printStream;
        this.tmallOrderBean = tmallOrderBean;
        this.tmallResponseService = tmallResponseService;
        this.asynExecutor = asynExecutor;
        this.tmallRetUrl = tmallRetUrl;
        this.pubKeyValue = pubKeyValue;
	}
	
	@Override
	public int getProtocolType() {
		
		return 0;
	}
  
	@Override
	public void onCallResult(CallParam callParam) {
		XmlMessage ack = null;
		Object response = null;
		if (callParam.getResponse() != null) {
			response = callParam.getResponse();
		} else if (callParam.getRecvResponse() != null) {
			response = callParam.getRecvResponse();
		}
		if (response == null) {
			_log.info("================response == null");
			_log.info("================callParam.getRetCode():"+callParam.getRetCode());
			ack = SoapChannel.createERRAnwser(callParam.getSessionId(),callParam.getRetCode() == 3002 ? 11202 : callParam.getRetCode(), callParam.getResultMsg());
		} else {
			if (response instanceof Message) {// CCA -> XML
				ack = BuzProcessorManager.getInstance().convertMessageToAck(callParam);
				_log.info("================isMessage===andData="+ack.getDATA());
			} else if (response instanceof XmlMessage) {
				ack = (XmlMessage) response;
				_log.info("================isXmlMessage===andData="+ack.getDATA());
			} else {
				_log.warn("unknown response type:" + callParam.getResponse().getClass().getName());
			}
		}
		String respXML = "";
		try {
			if (response instanceof Message) {
				_log.info("================isMessage");	
				ack = BuzProcessorManager.getInstance().convertMessageToAck(callParam);
			}else if (response instanceof XmlMessage) {
				XmlMessage xmlMessage=(XmlMessage) response;
				_log.info("getResponse:XmlMessage:data{}",xmlMessage.getDATA());
			}
			respXML = convertResponseString(response,callParam.getServiceResultCode());
			byte[] resp = respXML.getBytes("GBK");
			ack.setLength(resp.length);
			ack.setMsgTime(System.currentTimeMillis());
			printStream.write(resp);
			printStream.close();
			callParam.setResponse(ack);
			if (callParam.getRetCode() == Constants.ResultCode.SUCCESS) {// 成功的消息，请求应答入库
				MessageDetail detail = new MessageDetail();
				detail.setBusinessCallId(callParam.getBussinessCallId());
				detail.setSessionId(callParam.getSessionId());
				detail.setServiceContextId(callParam.getServiceContextId());
				detail.setMessageType(MessageType.WSA);
				detail.setDetails(ack.getDATA());
				detail.setMsgTime(new Date(ack.getMsgTime()));
				detail.setOpType("send");
				detail.setHostId(callParam.getUserName());
				MessageDetailCacheManager.getInstance().add(detail);
			}
			TaskManager.taskProcess(callParam);
			_log.info("http response(taobao) " + respXML);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}


	private String convertResponseString(Object answer, int serviceResultCode)
	{
		_log.info("===========serviceResultCode="+serviceResultCode);
		_log.info("===========isMessage"+(answer instanceof Message));
		String response = "";
		Map<String,String> data = new HashMap<String, String>();
		String xmlMessageData="";
		try {
			data.put("tbOrderNo",tmallOrderBean.getTbOrderNo());
			data.put("coopOrderNo","");
			data.put("coopOrderSnap","ReCharge");
			XmlMessage ack = null;
			if (answer instanceof XmlMessage) {
				XmlMessage xmlMessage=(XmlMessage) answer;
				xmlMessageData = xmlMessage.getDATA();
				_log.info("getResponse2:XmlMessage:data{}",xmlMessageData);
				if(xmlMessageData.indexOf("<Result>") >= 0) {
					serviceResultCode=Integer.valueOf( xmlMessageData.substring(xmlMessageData.indexOf("<Result>"), xmlMessageData.indexOf("</Result>")));
				}else {
					serviceResultCode=-1;
				}
				
			}
			_log.info("===========serviceResultCode="+serviceResultCode);
			if (serviceResultCode == 0 ) {
				String rechargeState = "0";
				String operTime = "";
				if (answer instanceof Message) {
					try{
				        //service_infomation
				        AVP avp = ((Message)answer).find(Constants.DIAMETER_AVP_SERVICE_INFOMATION,Constants.DIAMETER_VENDOR_3GPP);
				        AVP_Grouped avpServiceInfomation = new AVP_Grouped(avp);
					    //rechage_state
					    AVP avpRechageState = avpServiceInfomation.find(82013,Constants.DIAMETER_VENDOR_CT);
					    if (avpRechageState != null)
					    	rechargeState = new AVP_UTF8String(avpRechageState).queryValue();
					    //oper_time
					    AVP avpOperTime = avpServiceInfomation.find(5073,Constants.DIAMETER_VENDOR_CT);
						if (avpOperTime != null)
						    operTime = new AVP_UTF8String(avpOperTime).queryValue();				
					}catch(Exception e){
						_log.info("convertResponseString get answer Avps message error,msg = {} ",e.getMessage());
					}
				}else {
					rechargeState = xmlMessageData.substring(xmlMessageData.indexOf("<State>"), xmlMessageData.indexOf("</State>"));
					operTime = xmlMessageData.substring(xmlMessageData.indexOf("<StartTime>"), xmlMessageData.indexOf("</StartTime>"));
				}
				
				//rechargeState: 0 没有记录, 当为此值时,下面几项都填 0;1 充值成功;2 已经返销
				if (rechargeState.equals("1")){
					data.put("coopOrderStatus",TMallChannel.STATUS_SUCCESS);
					data.put("coopOrderSuccessTime",operTime);
					data.put("failedCode","");
					data.put("failedReason","");
					TreeMap<String,String> paraMap = new TreeMap<String, String>();
					paraMap.put("coopId",tmallOrderBean.getCoopId());
					paraMap.put("tbOrderNo",data.get("tbOrderNo"));
					paraMap.put("coopOrderNo",data.get("tbOrderNo"));
					paraMap.put("coopOrderSnap",data.get("coopOrderSnap"));
					paraMap.put("coopOrderStatus",data.get("coopOrderStatus"));
					paraMap.put("coopOrderSuccessTime",data.get("coopOrderSuccessTime"));
					String source = "";
					for(Entry<String,String> entry:paraMap.entrySet())
					{
						source += entry.getKey()+entry.getValue();
					}
					source = source + pubKeyValue;
					String sign = SignUtilsImpl.getTmallSign(source);
					paraMap.put("sign",sign);
					TMallRetTask task = new TMallRetTask(tmallRetUrl, paraMap);
					asynExecutor.execute(task);
				}else if(rechargeState.equals("2")){
					data.put("coopOrderStatus",TMallChannel.CANCEL);
					data.put("coopOrderSuccessTime","");
					data.put("failedCode","901");
					data.put("failedReason","");
					TreeMap<String,String> paraMap = new TreeMap<String, String>();
					paraMap.put("coopId",tmallOrderBean.getCoopId());
					paraMap.put("tbOrderNo",data.get("tbOrderNo"));
					paraMap.put("coopOrderNo",data.get("tbOrderNo"));
					paraMap.put("coopOrderStatus",data.get("coopOrderStatus"));
					paraMap.put("failedCode",data.get("failedCode"));
					paraMap.put("failedReason",data.get("failedCode"));
					String source = "";
					for(Entry<String,String> entry:paraMap.entrySet()){
						source += entry.getKey()+entry.getValue();
					}
					source = source + pubKeyValue;
					String sign = SignUtilsImpl.getTmallSign(source);
					paraMap.put("sign",sign);
					TMallRetTask task = new TMallRetTask(tmallRetUrl, paraMap);
					asynExecutor.execute(task);
				}else{
					data.put("coopOrderStatus",TMallChannel.REQUEST_FAIL);
					data.put("coopOrderSuccessTime","");
					data.put("failedCode","0104");
					data.put("failedReason","");				
				}
			} else if (serviceResultCode == 158 || serviceResultCode == 517 || serviceResultCode == 11203) {
				data.put("coopOrderStatus","UNDERWAY");
				data.put("coopOrderSuccessTime","");
				data.put("failedCode", "");//淘宝订单号找不到对应的自己系统的订单 0104
				data.put("failedReason","");
			}else if (serviceResultCode == -1){
				data.put("coopOrderStatus","UNDERWAY");
				data.put("coopOrderSuccessTime","");
				data.put("failedCode", "");//淘宝订单号找不到对应的自己系统的订单 0104
				data.put("failedReason","");
			}else {
				data.put("coopOrderStatus",TMallChannel.REQUEST_FAIL);
				data.put("coopOrderSuccessTime","");
				data.put("failedCode", "0104");
				data.put("failedReason","");
			}
		} catch (Exception e) {
			data.put("coopOrderStatus","UNDERWAY");
			data.put("coopOrderSuccessTime","");
			data.put("failedCode", "");//淘宝订单号找不到对应的自己系统的订单 0104
			data.put("failedReason","");
		}
		response = tmallResponseService.getResponse(data);
		return response;
	}
}
